﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;

using BlueCMS.Core;
using BlueCMS.Core.Entities;
using BlueCMS.Core.Services;

namespace BlueCMS.Core.Pages
{
    public class ContentRegion : Control, INamingContainer
    {
        IList<PageletInstance> mPagelets;
        bool mIsEditMode;
        string mRegionName;
        Webpage mWebpage;

        public ContentRegion(string regionName, bool isMasterRegion, Webpage webpage)
        {
            mWebpage = webpage;
            mRegionName = regionName;
            if (isMasterRegion)
            {
                mPagelets = PageletService.GetPageletInstancesForRegionAndTemplate(regionName, webpage.Template);
                mIsEditMode = CmsSession.RenderMode == RenderMode.TemplateEdit;
            }
            else
            {
                mPagelets = PageletService.GetPageletInstancesForRegionAndWebpage(regionName, webpage);
                mIsEditMode = CmsSession.RenderMode == RenderMode.SiteEdit;
            }
        }

        protected override void CreateChildControls()
        {
            HtmlGenericControl span = new HtmlGenericControl("span");
            Controls.Add(span);

            if (mIsEditMode)
            {
                if (UserService.UserHasPermissionForNode(CmsApplication.CmsUser, "NODE", "EDIT", CmsApplication.CmsNode))
                {
                    // Add toolbar for region
                    ContentRegionToolbarBase control = (ContentRegionToolbarBase)Page.LoadControl("~/_System/Controls/ContentRegionToolbar.ascx");
                    control.Webpage = mWebpage;
                    control.Template = mWebpage.Template;
                    control.RegionName = mRegionName;
                    span.Controls.Add(control);
                }
                span.Attributes.Add("class", "BCMS-ContentRegion-EditMode");
            }
            else
            {
                span.Attributes.Add("class", "BCMS-ContentRegion-DisplayMode");
            }

            foreach (PageletInstance pi in mPagelets)
            {
                span.Controls.Add(new PageletRegion(pi, mIsEditMode));
            }
        }
    }
}
